package edu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import edu.domain.Goods;
import edu.domain.User;
import edu.dto.CountDto;
import edu.service.GoodsService;
import edu.service.OrdersService;
import edu.service.UserService;
import edu.support.base.controller.AdminBaseController;
import edu.support.mybatis.MybatisWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Calendar;
import java.util.List;

import static edu.config.ConstantConfig.CATEGORY_LIST;

/**
 * @date 15:30
 */
@Controller
public class WebIndexController extends AdminBaseController {

    private static final Logger log = org.slf4j.LoggerFactory.getLogger(WebIndexController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private OrdersService ordersService;

    /**
     * 首页
     * 推荐列表
     *
     * @return
     */
    @RequestMapping("/")
    public String index(Model model) {
        request.setAttribute("page", "home");
        session.setAttribute("CATEGORY_LIST", CATEGORY_LIST);

        int time = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        List<CountDto> countDtos = ordersService.countByTime(time < 12 ? "AM" : "PM");

        // 根据条件排序  推荐这个时间段卖的最好的书
        String orderBy = "FIELD(category";
        for (CountDto dto : countDtos) {
            orderBy = orderBy + ",'" + dto.getName() + "'";
        }
        orderBy = orderBy + ")";

        // 没有订单数据的时候，默认排序
        if (countDtos.size() == 0) {
            orderBy = "create_time";
        }

        QueryWrapper<Goods> wrapper = new MybatisWrapper<Goods>().orderByDesc(orderBy);

        // 值推荐排名前十的
        PageHelper.startPage(1, 10);
        List<Goods> goodsList = goodsService.list(wrapper);
        model.addAttribute("goodsList", goodsList);

        // 最新的前五个  滚动
        PageHelper.startPage(1, 4);
        List<Goods> topList = goodsService.list(new QueryWrapper<Goods>()
                .eq("status", "上架")
                .orderByDesc("create_time"));
        model.addAttribute("topList", topList);

        initCartNum();
        return "index";
    }

    /**
     * 登录页
     *
     * @param name
     * @param model
     * @return
     */
    @RequestMapping("login")
    public String login(String name, Model model) {
        return "admin/login";
    }

    /**
     * 注册页
     *
     * @param name
     * @param model
     * @return
     */
    @RequestMapping("register")
    public String register(String name, Model model) {
        return "admin/register";
    }


    /**
     * 注册
     *
     * @return
     */
    @PostMapping("register")
    public String register(String username, String password, String repassword, String phone, RedirectAttributes attributes) {
        log.info("用户注册" + username);
        if (!password.equalsIgnoreCase(repassword)) {
            return redirect("/register", "两次密码不一样", attributes);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", username);
        int count = userService.count(wrapper);
        if (count == 0) {
            User user = new User();
            user.setRole("user");
            user.setNickname(username);
            user.setUsername(username);
            user.setPassword(passwordEncoder.encode(password));
            userService.save(user);
            return redirect("/login", "注册成功，请登录", attributes);
        } else {
            return redirect("/register", "该用户名已经注册过", attributes);
        }
    }

    /**
     * 个人信息
     *
     * @param model
     * @return
     */
    @RequestMapping("info")
    public String info(Model model) {
        User user = userService.getById(loginUserId());
        model.addAttribute(user);
        return "info";
    }

    /**
     * 更新个人信息
     *
     * @param model
     * @return
     */
    @RequestMapping("update")
    public String update(User user, RedirectAttributes model) {
        user.setId(loginUserId());
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(null);
        }
        userService.updateById(user);
        return refresh("更新成功", model);
    }

}
